<?php

 function filter($string) {
	$string = str_replace("\"", "", $string);
	$string = str_replace("'", "", $string);
	$string = str_replace("\r", "", $string);
	$string = str_replace("\n", "", $string);
	return $string;
 }
 
function get_ArmiesNextTurn($player,$NumCountries,$NumCards){
	$result = mysql_query("SELECT sum(bonus) as sBonus FROM risk_continents WHERE owner='$player'");
	$row 	= mysql_fetch_array($result, MYSQL_ASSOC);	
	$minANT = floor($NumCountries / 3);
	$maxANT = $minANT;
	if ($minANT < 3) {  $minANT = 3; }
	$minANT += $row['sBonus'];	
	if ($NumCards >= 3) {
		global $armytrades;
		$result 	= mysql_query("SELECT TradeIndex FROM risk_config");
		$row 		= mysql_fetch_array($result, MYSQL_ASSOC);
		$nextindex 	= $row['TradeIndex'];
	#	$result 	= mysql_query("SELECT NextTrade FROM risk_config");
	#	$row 		= mysql_fetch_array($result, MYSQL_ASSOC);
	#	$Trade 		= $row['NextTrade'];
		while ($NumCards >= 5) {
			$minANT 	+= $armytrades[$nextindex++];
			$NumCards 	-= 3;
		}
		$maxANT = $minANT;		
		// GET NUM ARMIES
		while ($NumCards >= 3) {
			$maxANT 	+= $armytrades[$nextindex++];
			$NumCards 	-= 3;
		}
	}

	if ($minANT < 3) $minANT = 3;
	if ($maxANT > $minANT) $minANT = $minANT . " to " . $maxANT;
	return $minANT;
}
	
function SetContinentOwners(){
	$cdb = new class_mysql;
	$cdb2 = new class_mysql;
	$cdb->select("SELECT owner, continent FROM risk_countries WHERE owner > '0' ORDER BY continent");
	$row        = $cdb->fetchArray();
	$pcontinent = $row['continent'];
	$powner     = $row['owner'];
	$same       = true;	
	while ($row = $cdb->fetchArray()) {
		if ($row['continent'] == $pcontinent) {
			if ($row['owner'] != $powner) { $same = false; }
		} else {
			if ($same) {
				$cdb2->query("UPDATE risk_continents SET owner='$powner' WHERE num='$pcontinent'"); 
			} else {
			    $cdb2->query("UPDATE risk_continents SET owner='0' WHERE num='$pcontinent'"); 
			}
			$pcontinent = $row['continent'];
			$powner     = $row['owner'];
			$same       = true;
		}
	}
	if ($same) {
		$cdb->query("UPDATE risk_continents SET owner='$powner' WHERE num='$pcontinent'");
	} else {
			    $cdb2->query("UPDATE risk_continents SET owner='0' WHERE num='$pcontinent'"); 
			}
}


function NextPlayersTurn() {
	
	$cdb = new class_mysql;
	$cdb->select("SELECT CurrentGame FROM risk_config");
	$row = $cdb->fetchArray();
	if ($row['CurrentGame'] != "Deploying") {
		$cdb->query("UPDATE risk_config SET TurnStatus='NewTurn'");
	}
	$cdb->select("SELECT num, turnorder FROM risk_players WHERE turnflag='1'");
	$row 		= $cdb->fetchArray();
	$nextturn 	= $row['turnorder'] + 1;

	$cdb->query("UPDATE risk_players SET turnflag='0' WHERE num='".$row['num']."'");
	$cdb->select("SELECT 1 FROM risk_players WHERE turnorder='$nextturn'");
	if ($cdb->getRecords() == 0) {
		$cdb->query("UPDATE risk_players SET turnflag='1' WHERE turnorder='1'");
	} else {
		$cdb->query("UPDATE risk_players SET turnflag='1' WHERE turnorder='$nextturn'");
	}
	$cdb->select("SELECT username FROM risk_players WHERE turnflag='1'");
	$row 		= $cdb->fetchArray();
	$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",\"<b>* ".$row['username']."'s turn.</b>\")");
	$risk = new class_risk;
	$risk->check4botmove();
}

function CommonBorder($c1, $c2) {
	$cdb = new class_mysql;
	$cdb->select("SELECT borders FROM risk_countries WHERE num='$c1'");
	$row 		= $cdb->fetchArray();
	if (in_array($c2, explode(",",$row['borders']))) { return true; } else { return false; }
}

function EOTCheckForCard($risk_usernum) {
	$cdb = new class_mysql;
	// CHECK FOR CARD
	$cdb->select("SELECT cardflag FROM risk_players WHERE num='$risk_usernum'");
	$row = $cdb->fetchArray();
	if ($row['cardflag'] == 1)	{
		$cdb->select("SELECT num FROM risk_cards WHERE owner='0'");
		while ($row = $cdb->fetchArray()) {
			$Cards[] = $row['num'];
		}
		shuffle($Cards);
		$cdb->update("UPDATE risk_cards SET owner='$risk_usernum' WHERE num='".$Cards[0]."'");
		$cdb->update("UPDATE risk_players SET cardflag='0' WHERE num='$risk_usernum'");		   
		// LOG
		$cdb->select("SELECT color, username FROM risk_players WHERE num='$risk_usernum'");
		$row = $cdb->fetchArray();
		$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\" ,
        \"<b><font color='".$row['color']."'>* ".$row['username']." got a card.</font></b>\")"); 
	}
}

function TradeCards($sCards, $risk_usernum) {
  $result = mysql_query("SELECT symbol,owner FROM risk_cards WHERE num IN ($sCards)");
  $row = mysql_fetch_array($result, MYSQL_ASSOC);
  $s1 = $row['symbol'];
  $ow1 = $row['owner'];
  $row = mysql_fetch_array($result, MYSQL_ASSOC);
  $s2 = $row['symbol'];
  $ow2 = $row['owner'];
  $row = mysql_fetch_array($result, MYSQL_ASSOC);
  $s3 = $row['symbol'];
  $ow3 = $row['owner'];

  if (($ow1 != $risk_usernum) || ($ow1 != $risk_usernum) || ($ow1 != $risk_usernum) ) { $ok2 = false; } else { $ok2=true; }
  
  if ($s1 == "W" || $s2 == "W" || $s3 == "W") { $ok = true; }
  elseif ($s1 == $s2 && $s2 == $s3) { $ok = true; }
  elseif ($s1 != $s2 && $s1 != $s3 && $s2 != $s3) { $ok = true; }
  else { $ok = false; }

  if (($ok) && ($ok2)) {
   global $armytrades;
   // GET NUM ARMIES
   $result = mysql_query("SELECT TradeIndex FROM risk_config");
   $row = mysql_fetch_array($result, MYSQL_ASSOC);
   if(!isset($armytrades[$row['TradeIndex']])) {
		$mnaxtradeindex = count($armytrades)-1;
	    $armytrades[$row['TradeIndex']] = $armytrades[$mnaxtradeindex];		
	}   
   $numarmies = $armytrades[$row['TradeIndex']];
   $nextindex = $row['TradeIndex'] + 1;
   $result = mysql_query("UPDATE risk_config SET TradeIndex='$nextindex'");

   // SET NUM ARMIES
   $result = mysql_query("SELECT armies, username FROM risk_players WHERE num='$risk_usernum'");
   $row = mysql_fetch_array($result, MYSQL_ASSOC);
   $newnumarmies = $numarmies + $row['armies'];
   $risk_username = $row['username'];
   $result = mysql_query("UPDATE risk_players SET armies='$newnumarmies', bottomsrc = 'deploy.php' WHERE num='$risk_usernum'");
   $result = mysql_query("UPDATE risk_cards SET owner='0' WHERE num IN ($sCards)");
   $result = mysql_query("UPDATE risk_config SET turnstatus='Deploying'");

   // LOG
   $result = mysql_query("SELECT color FROM risk_colors WHERE assigned='$risk_usernum'");
   $row = mysql_fetch_array($result, MYSQL_ASSOC);
   $mycolor = $row['color'];
   $result = mysql_query("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
              \"<b><font color='$mycolor'>* $risk_username traded in cards for 
                   <font color='gray'>$numarmies</font> armies.</font></b>\")");

   // CHECK FOR COUNTRY BONUS
   $result = mysql_query("SELECT num, name, owner, armies, continent FROM risk_countries WHERE num IN ($sCards)");
   while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    if ($row['owner'] == $risk_usernum) {
     $countryarmies = $row['armies'] + 2;
     $result2 = mysql_query("UPDATE risk_countries SET armies='$countryarmies' WHERE num='".$row['num']."'");
     $result2 = mysql_query("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
                \"<b><font color='$mycolor'>* $risk_username got a <font color='gray'>2</font>
                     army bonus for <font class='c".$row['continent']."'>".$row['name']."</font>.</font></b>\")");
    }
   }
    return true;
  }
  else return false;
}

function Victory($risk_usernum) {
	global $risk;
	$cdb = new class_mysql;
	$cdb->query("UPDATE risk_config SET CurrentGame='Complete', TurnStatus='$risk_usernum'");
	$risk->soapUpdateCurrentGame('Complete');
	
	$cdb->select("SELECT victories FROM risk_players WHERE num='$risk_usernum'");
	$row 		= $cdb->fetchArray();
	$victories 	= $row['victories'] + 1;
	$cdb->query("UPDATE risk_players SET victories='$victories' WHERE num='$risk_usernum'");
	return "document.location.href='win.php';";
}

function RemovePlayer($who) {
	$cdb = new class_mysql;
	$cdb->select("SELECT turnflag, turnorder FROM risk_players WHERE num='$who'");
	if ($cdb->getRecords() != 0) {
		$row 	= $cdb->fetchArray();
		$cturn 	= $row['turnorder'];
		$cdb->query("UPDATE risk_players SET turnflag='0', turnorder='0' WHERE num='$who'");
		$moreplayers = true;
		while($moreplayers) {
		   $nextturn = $cturn+1;
		    $cdb->select("SELECT num FROM risk_players WHERE turnorder='$nextturn'");
			if ($cdb->getRecords() == 0) {
			    $moreplayers = false;
			} else {
				$row = $cdb->fetchArray();
				$cdb->query("UPDATE risk_players SET turnorder='$cturn' WHERE num='".$row['num']."'");
				$cturn++;
			}
		}
		return true;
	} else { 
		return false; 
	}
}

function ForceTradeCards($limit, $risk_usernum) {
	$cdb = new class_mysql;
	$cdb->select("SELECT 1 FROM risk_cards WHERE owner='$risk_usernum'");
	if ($cdb->getRecords() >= $limit) {
		return true;
	} else {
		return false;
	}
}

function ActionNewTurn($risk_usernum) {
	$cdb   	= new class_mysql;
	$r 		= false;
	$_SESSION['cb'] = false;
	SetContinentOwners();	
	$cb[0] = 0; $cb[1] = 0; $cb[2] = 0; $cb[3] = 0; $cb[4] = 0; $cb[5] = 0; $cb[6] = 0;	
	$cdb->select("SELECT TurnStatus FROM risk_config");
	$row = $cdb->fetchArray();
	$ts = $row['TurnStatus'];
	if ($row['TurnStatus'] == "NewTurn") {
		$cdb->query("UPDATE risk_config SET TurnStatus='Deploying'");		
		// STANDARD ARMY BONUS
		$cdb->select("SELECT * FROM risk_countries WHERE owner='$risk_usernum'");
		$NumCountries = $cdb->getRecords();		
		// CHECK FOR CONTINENT BONUS
		$cdb->select("SELECT sum(bonus) as sBonus FROM risk_continents WHERE owner='$risk_usernum'");
		$row = $cdb->fetchArray();
		if ($NumCountries < 9) { $newarmies = 3; } else { $newarmies = floor($NumCountries / 3); }		
		$newarmies += $row['sBonus'];		
		$cdb->query("UPDATE risk_players SET armies='$newarmies',bottomsrc = 'deploy.php' WHERE num='$risk_usernum'");		
		// SET BONUSES IN SESSION
		$cdb->select("SELECT num, bonus FROM risk_continents WHERE owner='$risk_usernum' ORDER BY num");
		while ($row = $cdb->fetchArray()) {
			$_SESSION['cb'][$risk_usernum][$row['num']] = $row['bonus'];
		}
		$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
			 \"<b>Player $risk_usernum got $newarmies.</b>\")");
		$r = true;
	}
	return $r;
}


function ActionDeploy($mycountry,$mynumarmies,$risk_usernum){
	global $risk;
	$cdb   			= new class_mysql;
	$null 			= NULL;
	$cant 			= NULL;
	$attack 		= NULL;
	if (isset($mycountry) && $mycountry != $null) { 
		// CHECK TO SEE IF IT IS THE PLAYER'S TURN
		$cdb->select("SELECT turnflag, username FROM risk_players WHERE num='$risk_usernum'");
		$row 	 	= $cdb->fetchArray();
		$username 	= $row['username'];
		if ($row['turnflag'] == 1) {
			// CHECK FOR INITIAL DEPLOYMENT
			$cdb->select("SELECT CurrentGame FROM risk_config");
			$row 	 = $cdb->fetchArray();
			if ($row['CurrentGame'] == 'Deploying' && $mynumarmies > 1) {
				$cant = "You can only deploy 1 army during the initial deployment.";
			} else {
				$CG 		= ($row['CurrentGame'] == 'Deploying');
				// CHECK TO SEE IF PLAYER HAS ENOUGH ARMIES
				$cdb->select("SELECT armies, color FROM risk_players WHERE num='$risk_usernum'");
				$row 			 	= $cdb->fetchArray();
				$mycolor			= $row['color'];
				$playernumarmies 	= $row['armies'];
				if ($playernumarmies >= $mynumarmies) {
					// GET CURRENT NUM ARMIES ON COUNTRY
					$cdb->select("SELECT armies FROM risk_countries WHERE num='$mycountry'");
					$row 		= $cdb->fetchArray();
					$numarmies 	= $row['armies'];
					if ($CG)  {
						$DeployNextTurn = true;
						$ok 			 = true;
					} else {
						// CHECK CARDS / FORCE TRADE
						if (ForceTradeCards(5,$risk_usernum)) {
							$cant = "You must trade in cards.";
						} else {
							// ENSURE PLAYER RESPECTS BONUS ARMIES => CONTINENTS
							$cdb->select("SELECT continent FROM risk_countries WHERE num='$mycountry'");
							$row 		= $cdb->fetchArray();
							// If deploying to continent with bonus, adjust bonuses
							if (isset($_SESSION['cb'][$risk_usernum][$row['continent']])){
								$restore 	= $_SESSION['cb'][$risk_usernum][$row['continent']];
							} else { $restore = 0; }
							if (isset($_SESSION['cb'][$risk_usernum][$row['continent']]) && $_SESSION['cb'][$risk_usernum][$row['continent']] > 0)  {
								$_SESSION['cb'][$risk_usernum][$row['continent']] -= $mynumarmies;
								if ($_SESSION['cb'][$risk_usernum][$row['continent']] < 0) $_SESSION['cb'][$risk_usernum][$row['continent']] = 0;
							}
							if(is_array($_SESSION['cb'][$risk_usernum])) {
							if (($playernumarmies - $mynumarmies) < array_sum($_SESSION['cb'][$risk_usernum])) {
								// If deploying to continent with bonus, re-adjust bonuses
								$_SESSION['cb'][$risk_usernum][$row['continent']] = $restore;							
								$cant = "You need to deploy your continent bonuses on the same continent.\\nHere are your remaining bonuses:\\n";
								foreach ($_SESSION['cb'][$risk_usernum] as $key => $value) {
									if ($value > 0)  {
										$cdb->select("SELECT name FROM risk_continents WHERE num='$key'");
										$row 		= $cdb->fetchArray();
										$cant 	   .= "\\n". $row['name'] . ": ". $_SESSION['cb'][$risk_usernum][$key];
									}
								} //!foreach
							} else { $ok = true;}
							} else { $ok = true;}
						} // !ELSE - TRADE CARDS
					} // ! CHECK CONTINENT BONUSES	
					if ($ok) {
						// ADD ARMIES TO COUNTRY, REMOVE ARMIES FROM PLAYER
						$numarmies   += $mynumarmies; 
						$cdb->query("UPDATE risk_countries SET armies='$numarmies' WHERE num='$mycountry'");
						$cdb->select("SELECT armies FROM risk_players WHERE num='$risk_usernum'");
						$row 			= $cdb->fetchArray();
						$newnumarmies = $row['armies'] - $mynumarmies;
						$cdb->query("UPDATE risk_players SET armies='$newnumarmies' WHERE num='$risk_usernum'");   
						// LOG
						$cdb->select("SELECT name, continent FROM risk_countries WHERE num='$mycountry'");
						$row 			= $cdb->fetchArray();
						$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
							 \"<b><font color='$mycolor'>* $username deployed <font color='gray'>$mynumarmies</font>
							 armies in <font class='c".$row['continent']."'>".$row['name']."</font>.</b></font>\")");
					}
				
				} else {	$cant = "You don\'t have that many armies."; $newnumarmies = 1;   }
			}
		} else { $cant = "It isn\'t your turn.";  $newnumarmies = 1; }
		
		if ($DeployNextTurn)  {
			// CHECK TO SEE IF INIT DEPLOY IS OVER
			$cdb->select("SELECT sum(armies)  FROM risk_players");
			$row = $cdb->fetchArray();
			if ($row[0] == 0)  {
				$cdb->query("UPDATE risk_config SET CurrentGame='Active'");
				$risk->soapUpdateCurrentGame('Active');
			}
			NextPlayersTurn();
		} else {
			// NOT INIT DEPLOY
			if ($newnumarmies == 0 && $ok) {
			   $cdb->query("UPDATE risk_config SET TurnStatus='Attacking'");
			   $cdb->query("UPDATE risk_players SET bottomsrc='attack.php' WHERE num='$risk_usernum'");			  
			   $attack = 1;
		    }
		}		
	}
	$r = array();
	$r['cant'] = $cant;
	$r['attack'] = $attack;
	return $r;
}


function ActionAttack($myfrom,$myto,$mynumarmies,$risk_usernum) {

	$cdb   			= new class_mysql;
	$cant 			= NULL;
	$null 			= NULL;
	$takeover 		= NULL;
	
	if (isset($mynumarmies) && $mynumarmies != $null) { 
		// CHECK TO SEE IF IT IS THE PLAYER'S TURN
		$cdb->select("SELECT turnflag,username FROM risk_players WHERE num='$risk_usernum'");
		$row = $cdb->fetchArray();
		$username 	= $row['username'];
		if ($row['turnflag'] == 1) {
			// CHECK FOR COMMON BORDER
			if (CommonBorder($myfrom, $myto))  {
			   // ENSURE PLAYER DOESN'T ATTACK HIMSELF
			   $cdb->select("SELECT owner FROM risk_countries WHERE num='$myto'");
			   $row = $cdb->fetchArray();	
				if ($row['owner'] != $risk_usernum)  {				
					if (ForceTradeCards(5,$risk_usernum)) {
						$cant = "You must trade in cards.";
					} else {
						// CHECK NUM ARMIES
						$cdb->select("SELECT armies FROM risk_countries WHERE num='$myfrom'");
						$row 	 = $cdb->fetchArray();
						if ($row['armies'] > $mynumarmies) {
							$AttArmies 	= $row['armies'];
							$AttDice 	= $mynumarmies;
							// GET NUM DEFENSE
							$cdb->select("SELECT armies FROM risk_countries WHERE num='$myto'");
							$row 		= $cdb->fetchArray();
							$DefArmies 	= $row['armies'];
							if ($DefArmies > 1) { $DefDice = 2;  } else {  $DefDice = 1;  }
							// ROLL
							while($AttDice > 0) { srand((float)microtime()*1000000); $AttRolls[] = rand(1,6); $AttDice --; }
							while($DefDice > 0) { srand((float)microtime()*1000000); $DefRolls[] = rand(1,6); $DefDice --; }
							// COMPARE ROLLS
							rsort($AttRolls);
							rsort($DefRolls);
							// LOG
							$cdb->select("SELECT name, continent FROM risk_countries WHERE risk_countries.num='$myfrom'");
							$row 		= $cdb->fetchArray();
							$from 		= $row['name'];
							$fromc 		= $row['continent']; 
							$cdb->select("SELECT name, continent,  owner FROM risk_countries  WHERE risk_countries.num='$myto'");							
							$row 		= $cdb->fetchArray();
							$to 		= $row['name'];
							$toc 		= $row['continent'];	  
							$too 		= $row['owner'];
							$cdb->select("SELECT username FROM risk_players  WHERE risk_players.num='$too'");							
							$row 		= $cdb->fetchArray();
							$tou 		= $row['username'];	  
							$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
								\"<b><font color='$fromcol'>* $username is attacking <font class='c".$toc."'>$to</font>
								from <font class='c".$fromc."'>$from</font>
								with <font color='gray'>$mynumarmies</font> armies.</font></b>\")"); 
							$strAttRolls = "";
							$strDefRolls = "";
	
							foreach($AttRolls as $roll) $strAttRolls .= "<font color='gray'>, </font>" . $roll;
							foreach($DefRolls as $roll) $strDefRolls .= "<font color='gray'>, </font>" . $roll;
							$strAttRolls = substr($strAttRolls, 28, strlen($strAttRolls));
							$strDefRolls = substr($strDefRolls, 28, strlen($strDefRolls));
	
							$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\", 
								  \"<b><font color='$tocol'>* $tou : $strDefRolls.</b></font>\")");
							
							$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
								  \"<b><font color='$fromcol'>* $username : $strAttRolls.</b></font>\")");
	
							$aLost = 0;
							$dLost = 0;
	
							// COMPARE ROLL 1
							if ($AttRolls[0] > $DefRolls[0])  { $DefArmies --; $dLost ++; } else { $AttArmies --; $aLost ++;  }
	
							// IF 2 ROLLS
							if ($AttRolls[1] != $null && $DefRolls[1] != $null) {
								// COMPARE ROLL 2
								if ($AttRolls[1] > $DefRolls[1]) { $DefArmies --; $dLost ++; } else { $AttArmies --; $aLost ++;	}
							}
	
							// CHECK FOR TAKEOVER
							if ($DefArmies == 0) { $takeover = true; }
							
							$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
							  \"<b><font color='$tocol'>* $tou lost <font color='gray'>$dLost</font>.</b></font>\")");
							
							$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
							  \"<b><font color='$fromcol'>* $username lost 
							  <font color='gray'>$aLost</font>.</b></font>\")");
							
							$cdb->query("UPDATE risk_countries SET armies='$AttArmies' WHERE num='$myfrom'");
							$cdb->query("UPDATE risk_countries SET armies='$DefArmies' WHERE num='$myto'");
						} else  { $cant = "You don\'t have enough armies."; }
					}
				} else { $cant = "You can\'t attack yourself.";  }
			} else { $cant = "You can\'t attack that country."; }
		} else { $cant = "It\'s not your turn."; }
		if ($takeover == true) {
			$takeover = "takeover.php?from=$myfrom&to=$myto&numarmies=$mynumarmies"; 
			$cdb->query("UPDATE risk_config SET TurnStatus='Takeover'");
			$cdb->query("UPDATE risk_players SET bottomsrc='$takeover' WHERE num='$risk_usernum'");	 
		}		
	}
	
	
	$r = array();
	$r['cant'] = $cant;
	$r['takeover'] = $takeover;
	return $r;
}

function ActionTakeover($myfrom,$myto,$mynumarmies, $risk_usernum) {
	global $risk;
	$cdb   	= new class_mysql;
	$ok 	= NULL;
	$exit 	= NULL;
	if ($mynumarmies != $null)	{ 
		// SET FROM
		$cdb->select("SELECT username, takeovers, kills FROM risk_players WHERE num='$risk_usernum'");
		$row 			= $cdb->fetchArray();	
		$risk_username 	= $row['username'];		
		$risk_takeovers = $row['takeovers'];		
		$risk_kills 		= $row['kills'];		
		$cdb->select("SELECT armies FROM risk_countries WHERE num='$myfrom'");
		$row 			= $cdb->fetchArray();	
		$newnumarmies 	= $row['armies'] - $mynumarmies;	 
		$cdb->query("UPDATE risk_countries SET armies='$newnumarmies' WHERE num='$myfrom'");	
		// SET TO  // Get Defender Num
		$cdb->select("SELECT owner FROM risk_countries WHERE num='$myto'");
		$row 			= $cdb->fetchArray();	
		$defender 		= $row['owner'];	
		$cdb->query("UPDATE risk_countries SET armies='$mynumarmies', owner='".$risk_usernum."' WHERE num='$myto'");	
		// RESET CONTINENTS
		SetContinentOwners();	
		// DONE
		$risk_takeovers++;
		$cdb->query("UPDATE risk_players SET takeovers='$risk_takeovers' WHERE num='$risk_usernum'");
		$cdb->select("SELECT name, continent, armies FROM risk_countries WHERE risk_countries.num='$myto'");
		$row 			= $cdb->fetchArray();	
		$mycolor		= $row['color'];	
		$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
			\"<b><font color='$mycolor'>* $risk_username has taken <font class='c".$row['continent']."'>
			".$row['name']."</font> and moved in <font color='gray'>".$row['armies']."</font> armies.</font>\")");
	
		$cdb->query("UPDATE risk_config SET TurnStatus='Attacking'");
		$cdb->query("UPDATE risk_players SET bottomsrc='attack.php' WHERE num='$risk_usernum'");
		$cdb->query("UPDATE risk_players SET cardflag='1' WHERE num='$risk_usernum'");
		$ok = "DisplayBottom('attack.php');";	
	
		// CHECK FOR DEFENDER DEATH
		$cdb->select("SELECT 1 FROM risk_countries WHERE owner='$defender'");
		$count = $cdb->getRecords();
		if ($count == 0)  {
			RemovePlayer($defender);
			$cdb->query("UPDATE risk_players SET status='1' WHERE num='$defender'");
			$cdb->select("SELECT 1 FROM risk_cards WHERE owner='$defender'");
			$numcards = $cdb->getRecords();
			$cdb->query("UPDATE risk_cards SET owner='$risk_usernum' WHERE owner='$defender'");
			
			$cdb->select("SELECT losses FROM risk_players WHERE num='$defender'");
			$row 	= $cdb->fetchArray();
			$losses 	= $row['losses'] + 1;
			$cdb->query("UPDATE risk_players SET losses='$losses' WHERE num='$defender'");
			$risk_kills++;			
			$cdb->query("UPDATE risk_players SET kills='$risk_kills' WHERE num='$risk_usernum'");				
			// LOG
			$cdb->select("SELECT username FROM risk_players WHERE num='$defender'");
			$row 	= $cdb->fetchArray();
			$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
				  \"<b><font color='gray'>* ".$row['username']." died.</font>\")");	
			if ($numcards > 0)  {
				$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
				   \"<b><font color='$mycolor'>* $risk_username swiped
						<font color='gray'>$numcards</font> cards.</font>\")");
			}	
			// CHECK FOR VICTORY
			$cdb->select("SELECT num FROM risk_players WHERE status='10'");
			if ($cdb->getRecords() == 1)   $win = Victory($risk_usernum);
			// CHECK FOR GAME-Stop because the last human died
			$cdb->select("SELECT num FROM risk_players WHERE status='10' and num > 6");
			if ($cdb->getRecords() < 1)   { $exit = true; }
			
			
		}
	}
	$r = array();
	$r['ok'] = $ok;
	$r['win'] = $win;
	$r['exit'] = $exit;
	return $r;
}




function ActionFortify($mynumarmies,$myfrom,$myto, $risk_usernum) {
	$cdb   			= new class_mysql;
	$null 			= NULL;
	$cant 			= NULL;
	$ok 			= NULL;
	
	if ($mynumarmies != $null) { 
		// CHECK TO SEE IF IT IS THE PLAYER'S TURN
		$cdb->select("SELECT turnflag, username FROM risk_players WHERE num='$risk_usernum'");
		$row 	= $cdb->fetchArray();
		$risk_username = $row['username'];
		if ($row['turnflag'] == 1) {
			if ($mynumarmies > 0) {
				// CHECK FOR COMMON BORDER
				if (CommonBorder($myfrom, $myto)) {
					#if (ForceTradeCards(5,$risk_usernum)) {
					#   $cant = "You must trade in cards.";
					#} else {
						// ENSURE PLAYER OWNS BOTH COUNTRIES
						$cdb->select("SELECT owner FROM risk_countries WHERE num='$myto'");
						$row 	= $cdb->fetchArray();						
						if ($row['owner'] == $risk_usernum)  {
							// CHECK NUM ARMIES
							$cdb->select("SELECT armies FROM risk_countries WHERE num='$myfrom'");
							$row = $cdb->fetchArray();				
							if ($row['armies'] > $mynumarmies) {							
								$newnumarmiesFrom 	= $row['armies'] - $mynumarmies;
								$cdb->query("UPDATE risk_countries SET armies='$newnumarmiesFrom' WHERE num='$myfrom'");	
								$cdb->select("SELECT armies FROM risk_countries WHERE num='$myto'");
								$row 			 	= $cdb->fetchArray();
								$newnumarmiesTo 	= $row['armies'] + $mynumarmies;
								$cdb->query("UPDATE risk_countries SET armies='$newnumarmiesTo' WHERE num='$myto'");
								// LOG
								$cdb->select("SELECT name, continent FROM risk_countries WHERE num='$myfrom'");
								$row     = $cdb->fetchArray();
								$from    = $row['name'];
								$fromc   = $row['continent'];
								$fromcol = $row['color'];			
								$cdb->select("SELECT name, continent FROM risk_countries WHERE num='$myto'");
								$row     = $cdb->fetchArray();
								$to      = $row['name'];
								$toc     = $row['continent'];
								$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
								\"<b><font color='$fromcol'>* $risk_username moved $mynumarmies from
								<font class='c".$fromc."'>$from</font> to <font class='c".$toc."'>$to</font>.</font></b>\")");				
								EOTCheckForCard($risk_usernum);					
								$cdb->query("UPDATE risk_players SET bottomsrc='notmyturn.php' WHERE num='$risk_usernum'");
								$ok = true;
								NextPlayersTurn();
							} else {  $cant = "You don\'t have enough armies.";  }
						} else {  $cant = "You don\'t own these 2 countries.";  }
					#} // !FORCE TRADE
				} else { $cant = "These countries have no common borders."; }
			} else {
				// NO FORTIFY
				$cdb->select("SELECT color FROM risk_colors WHERE assigned='$risk_usernum'");
				$row 	= $cdb->fetchArray();
				$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
						\"<b><font color='".$row['color']."'>* $risk_username moved  nothing.</font></b>\")");
				EOTCheckForCard($risk_usernum);
				$cdb->query("UPDATE risk_players SET bottomsrc='notmyturn.php' WHERE num='$risk_usernum'");
				$ok = true;
				NextPlayersTurn();
				// !NO FORTIFY
			}
		} else { $cant = "It\'s not your turn."; }
	}
	
	$r 			= array();
	$r['ok'] 	= $ok;
	$r['cant'] 	= $cant;
	return $r;
		 
}




function ActionTrade($mycards,$risk_usernum) {
	$null 			= NULL;
	$ok 			= NULL;
	$cant 			= NULL;
	$cdb   			= new class_mysql;
	if ($mycards != $null)  { 
		// CHECK TO SEE IF IT IS THE PLAYER'S TURN
		$cdb->select("SELECT turnflag, TurnStatus FROM risk_players, risk_config WHERE num='$risk_usernum'");
		$row = $cdb->fetchArray();
		if     ($row['TurnStatus'] == "Deploying" && $row['turnflag'] == 1) $ok = true;
		elseif ($row['TurnStatus'] == "Attacking" && ForceTradeCards(5,$risk_usernum))    $ok = true;
		else   $cant = "You can\'t trade cards right now.";
	}
	if ($ok) {
		if(!TradeCards($mycards, $risk_usernum)) {
			$ok 	= false;
			$cant = "You did not trade in a matching set. You need to trade in 3 of a kind or 3 different cards.";
		} else { $ok = true; }
	}
	$r 			= array();
	$r['cant'] 	= $cant;
	$r['ok'] 	= $ok;
	return $r;
}


function getagent() {
  if (strstr($_SERVER['HTTP_USER_AGENT'],'Opera'))    {      
     $brows=ereg_replace(".+\(.+\) (Opera |v){0,1}([0-9,\.]+)[^0-9]*","Opera \\2",$_SERVER['HTTP_USER_AGENT']);
     if(ereg('^Opera/.*',$_SERVER['HTTP_USER_AGENT'])){
     $brows=ereg_replace("Opera/([0-9,\.]+).*","Opera \\1",$_SERVER['HTTP_USER_AGENT']);    }}
  elseif (strstr($_SERVER['HTTP_USER_AGENT'],'MSIE'))
     $brows=ereg_replace(".+\(.+MSIE ([0-9,\.]+).+","Internet Explorer \\1",$_SERVER['HTTP_USER_AGENT']);
  elseif (strstr($_SERVER['HTTP_USER_AGENT'],'Firefox'))
     $brows=ereg_replace(".+\(.+rv:.+\).+Firefox/(.*)","Firefox \\1",$_SERVER['HTTP_USER_AGENT']);
  elseif (strstr($_SERVER['HTTP_USER_AGENT'],'Mozilla'))
     $brows=ereg_replace(".+\(.+rv:([0-9,\.]+).+","Mozilla \\1",$_SERVER['HTTP_USER_AGENT']);
  else
     $brows=$_SERVER['HTTP_USER_AGENT'];
  return $brows;
} 

?>